package com.kpx.app.activity;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.kpx.app.R;
import com.kpx.app.base.ActivityBase;
import com.kpx.app.bean.LocationDetails;
import com.kpx.app.bean.AddressBean;
import com.kpx.app.http.HttpDataApi;
import com.kpx.app.http.HttpDataLoader;
import com.kpx.app.http.HttpDataReqUrl;
import com.kpx.app.http.HttpDataRequest;
import com.kpx.app.http.ResObj;
import com.kpx.app.utils.MyHashMap;
import com.kpx.app.utils.UIUtils;
import com.kpx.app.utils.datautils.FastJsonUtils;
import com.kpx.app.utils.uiutils.IntentUtil;
import com.kpx.app.utils.datautils.LogUtils;
import com.kpx.app.utils.StringUtil;
import com.kpx.app.utils.uiutils.ToastUtil;
import com.kpx.app.view.TitleView;
import com.kpx.app.wigdet.DialogFactoryImpl;

/**
 * User: 陈聪(617909447@qq.com)
 * Date: 2016-06-24
 * Time: 09:59
 * 订单确认页面
 */
public class ActivityOrderAddAddress extends ActivityBase {
    /**
     * 进入的方式 0增加地址，1修改地址
     */
    public static int type;
    /**
     * 标题栏
     */
    private TitleView title_view;
    /**
     * 选择性别
     */
    private RadioGroup rg_choice_sale;
    /**
     * 选择地址
     */
    private LinearLayout ll_change_address;
    /**
     * 地址描述
     */
    private TextView txt_address;
    /**
     * 联系人
     */
    private EditText et_name;
    /**
     * 输入详细门牌号
     */
    private EditText et_address_detail;
    /**
     * 电话号码
     */
    private EditText et_phone;
    private Button btn_delete;
    private AddressBean addressBean;
    private int sex;
    /**
     * 身份证
     */
    private EditText et_pon;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        UIUtils.setNotifyColor(this, R.color.title_color_grey_sm);
        setContentView(R.layout.activity_super_market_add_address);
        initTitle();
        initToView();
        setData();
    }

    @Override
    public void initview(@Nullable Bundle savedInstanceState) {

    }

    @Override
    public void initData() {

    }

    @Override
    public void onReceiver(Context context, Intent intent) {

    }

    private void initTitle() {
        title_view = (TitleView) findViewById(R.id.titleview);
        UIUtils.setNormalTitle(title_view, "新增地址");
        title_view.setTxtSize(0, 12);
        title_view.setRight("保存", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkData()) {
                    DialogFactoryImpl.newInstance(ActivityOrderAddAddress.this).showConfirmDialog("设置默认", "不用了", "是否将当前地址设置为默认地址？", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            switch (which) {
                                case DialogInterface.BUTTON_NEGATIVE:
                                    addressBean.setIsDefault(1);
                                    break;
                                case DialogInterface.BUTTON_POSITIVE:
                                    addressBean.setIsDefault(2);
                                    break;
                            }
                            saveOrUpdateAddress();
                        }
                    });
                }
            }
        }, R.color.white);
    }

    /**
     * 设置数据
     */
    private void setData() {
        if (type == 1) {
            addressBean = (AddressBean) getIntent().getExtras().getSerializable(getResources().getString(R.string.intent_key_bean));
            et_name.setText(addressBean.getReceiver());
            et_phone.setText(addressBean.getPhone());
            et_pon.setText(addressBean.getPno());
            txt_address.setText(addressBean.getRegion());
            if (addressBean.getSex() == 2) {//2女 1男
                sex = 2;
                rg_choice_sale.check(R.id.rb_women);
            } else {
                sex = 1;
                rg_choice_sale.check(R.id.rb_man);
            }
            et_address_detail.setText(addressBean.getAddress());
        } else {
            btn_delete.setVisibility(View.GONE);
            addressBean = new AddressBean();
        }

    }

    /**
     * 初始化相关view
     */
    private void initToView() {
        btn_delete = (Button) findViewById(R.id.btn_delete);
        rg_choice_sale = (RadioGroup) findViewById(R.id.rg_choice_sale);
        ll_change_address = (LinearLayout) findViewById(R.id.ll_change_address);
        txt_address = (TextView) findViewById(R.id.txt_address);
        et_name = (EditText) findViewById(R.id.et_name);
        et_pon = (EditText) findViewById(R.id.et_pon);
        et_address_detail = (EditText) findViewById(R.id.et_address_detail);
        et_phone = (EditText) findViewById(R.id.et_phone);

        rg_choice_sale.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_man:
                        sex = 2;
                        break;
                    case R.id.rb_women:
                        sex = 1;
                        break;
                }
            }
        });
        ll_change_address.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 地图地址
                Intent intent = new Intent();
                ActivityMap.BaiduMapConfig baiduMapConfig = new ActivityMap.BaiduMapConfig(true, true, false, false, null, null, true);
                intent.putExtra(ActivityMap.BAIDUMAP_CONFIG, baiduMapConfig);
                IntentUtil.gotoActivityForResult(ActivityOrderAddAddress.this, ActivityMap.class, intent, REQUEST_CODE_MAP_LOCATION);
            }
        });
        btn_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showLoadingDialog();
                MyHashMap map = new MyHashMap();
                map.put("rid", addressBean.getDmId() + "");
                new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
                    @Override
                    public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                        dissmissLoadingDialog();
                        if (result.getCode() == 0) {
                            finish();
                            ToastUtil.getInstance().showToast(ActivityOrderAddAddress.this, "删除成功");
                        } else {
                            ToastUtil.getInstance().showToast(ActivityOrderAddAddress.this, result.getMsg());
                        }
                    }

                    @Override
                    public void onRequestError(String url, int statusCode, String error) {
                        ToastUtil.getInstance().showToast(ActivityOrderAddAddress.this, error);
                    }

                }, null, null).POST(HttpDataReqUrl.URL_GET_ADDRESS_DELETE, true, map);

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_MAP_LOCATION:
                if (data == null) {
                    return;
                }
                LocationDetails locationDetails = (LocationDetails) data.getSerializableExtra(ActivityMap.LOCATION_RESULT_KEY);
                if (locationDetails != null) {
                    LogUtils.i("ActivityOrderAddAddress", "回传的结果为： " + locationDetails);
                    txt_address.setText(locationDetails.getProvince() + locationDetails.getCity() + locationDetails.getDistrict());
                    et_address_detail.setText(locationDetails.getDetailAddress());
                    addressBean.setLatitude(locationDetails.latitude);
                    addressBean.setLongitude(locationDetails.longitude);
                }
                break;
        }
    }

    /**
     * 打开地图
     */
    private final int REQUEST_CODE_MAP_LOCATION = 130;

    /**
     * 检查提交数据
     *
     * @return
     */
    private boolean checkData() {
        if (null == addressBean) {
            addressBean = new AddressBean();
        }
        if (TextUtils.isEmpty(et_name.getText().toString().trim())) {
            ToastUtil.getInstance().showToast(ActivityOrderAddAddress.this, "请输入姓名");
            return false;
        }
        if (TextUtils.isEmpty(et_phone.getText().toString().trim())) {
            ToastUtil.getInstance().showToast(ActivityOrderAddAddress.this, "请输入联系电话");
            return false;
        }
        if (!StringUtil.isValidatePhoneNumber(et_phone.getText().toString().trim())) {
            ToastUtil.getInstance().showToast(ActivityOrderAddAddress.this, "请输入正确的手机号码");
            return false;
        }
//        if (!TextUtils.isEmpty(et_pon.getText().toString().trim()) &&
//                !UIUtils.checkData("^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$", et_pon.getText().toString().trim())) {
//            ToastUtil.getInstance().showToast(ActivityOrderAddAddress.this, "请输入正确的身份证号码");
//            return false;
//        }
        if (TextUtils.isEmpty(txt_address.getText().toString().trim())) {
            ToastUtil.getInstance().showToast(ActivityOrderAddAddress.this, "请选择收货地址");
            return false;
        }
        if (TextUtils.isEmpty(et_address_detail.getText().toString().trim())) {
            ToastUtil.getInstance().showToast(ActivityOrderAddAddress.this, "请输入详细地址");
            return false;
        }
        addressBean.setReceiver(et_name.getText().toString().trim());
        addressBean.setRegion(txt_address.getText().toString().trim());
        addressBean.setAddress(et_address_detail.getText().toString().trim());
        addressBean.setPhone(et_phone.getText().toString().trim());
        addressBean.setSex(sex);
        addressBean.setPno(et_pon.getText().toString().trim());
        return true;
    }

    /**
     * 保存或修改地址
     * v1.0/app/user/subsidiary/addReceivingAddress
     * token,receiver(收货人),phone联系方式,region(广东省-深圳市),address(详细地址串),isDefault(默认地址1:是，2非)
     */
    private void saveOrUpdateAddress() {
        showLoadingDialog();
        MyHashMap map = new MyHashMap();
        map.put("receiver", addressBean.getReceiver());
        map.put("phone", addressBean.getPhone() + "");
        map.put("region", addressBean.getRegion());
        map.put("address", addressBean.getAddress());
        map.put("isDefault", addressBean.getIsDefault() + "");
        String url = "";
        if (type == 1) {
            url = HttpDataReqUrl.URL_GET_ADDRESS_EDIT;
            map.put("receiverId", addressBean.getDmId() + "");
        } else {
            url = HttpDataReqUrl.URL_GET_ADDRESS_ADD;
        }
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                dissmissLoadingDialog();
                if (result.getCode() == 0) {
                    addressBean = (AddressBean) result.getData();
                    Intent intent = new Intent();
                    intent.putExtra(getResources().getString(R.string.intent_key_bean), addressBean);
                    setResult(RESULT_OK, intent);
                    ActivityOrderAddAddress.super.finish();
                } else {
                    ToastUtil.getInstance().showToast(ActivityOrderAddAddress.this, result.getMsg());
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                ToastUtil.getInstance().showToast(ActivityOrderAddAddress.this, error);
            }

        }, AddressBean.class, HttpDataRequest.TYPE_OBJECT).POST(url, true, map);

    }

}
